/**
 *Copyright Marvell Inc
 */

package com.hisense.settings.base;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;

import com.hisense.settings.util.TvIntents;
import com.hisense.settings.util.WidgetManager;
import com.hisense.settings.util.Wrapper;
//import com.marvell.willowtv.framework.features.TvFramework;
//import com.marvell.willowtv.framework.util.atsc.ChannelEnumClass.ChannelDetails;

import java.util.List;

public class TVBaseDialog extends Activity {
    private static final String TAG = "TVBaseDialog";
    protected final int TIMEOUT_5SEC = 5000;
    private int mTimeOutValue = TIMEOUT_5SEC;
    private boolean isTimeOutStarted = false;
    private final int EXIT_KEY = 355;

    // Holds instance of broadcast receiver which will receiver CLOSE_APP event
    private BroadcastReceiver mReceiver;

    private final Handler mTimeOutHandler = new Handler();
    private Runnable mTimeOutRunnable = new Runnable() {
        @Override
        public void run() {
            TVBaseDialog.this.finish();
        }
    };
    // Holds the instance of USDTVBaseUtility
    private Context mContext = null;

    //private List<ChannelDetails> mChList = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getApplicationContext();
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(final Context context, final Intent intent) {
                if (intent.getAction().equals(TvIntents.INTENT_ACTION_CLOSE_APP)) {
                    Log.d(TAG, "receive intent " + TvIntents.INTENT_ACTION_CLOSE_APP);
                    finish();
                }
            }
        };
        final IntentFilter filter = new IntentFilter();
        filter.addAction(TvIntents.INTENT_ACTION_CLOSE_APP);
        registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startTimeOut();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopTimeOut();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    /**
     * Set timeout interval in msec
     * @param value
     *            in msec
     */
    protected void setTimeOut(int value) {
        mTimeOutValue = value;
    }

    /**
     * Get current timeout interval in msec
     */
    protected int getTimeOut() {
        return mTimeOutValue;
    }

    /**
     * Set runnable which is invoked when timeout expires
     * @param value
     *            Runnable
     */
    protected void setTimeOutRunnable(Runnable r) {
        stopTimeOut();
        mTimeOutRunnable = r;
    }

    /**
     * Get current timeout runnable
     */
    protected Runnable getTimeOutRunnable() {
        return mTimeOutRunnable;
    }

    /**
     * Start timeout
     */
    protected void startTimeOut() {
        isTimeOutStarted = true;
        refreshTimeOut();
    }

    /**
     * Stop timeout
     */
    protected void stopTimeOut() {
        isTimeOutStarted = false;
        if (getTimeOutRunnable() != null) {
            mTimeOutHandler.removeCallbacks(getTimeOutRunnable());
        }
    }

    /**
     * Refresh timeout
     */
    protected void refreshTimeOut() {
        if (isTimeOutStarted && getTimeOutRunnable() != null && getTimeOut() != 0) {

            // Remove any pending posts of Runnable that are in the message
            // queue.
            mTimeOutHandler.removeCallbacks(getTimeOutRunnable());

            /*
             * Causes the Runnable to be added to the message queue, to be run
             * after the specified amount of time elapses. The runnable will be
             * run on the thread to which this handler is attached.
             */
            mTimeOutHandler.postDelayed(getTimeOutRunnable(), getTimeOut());
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        refreshTimeOut();
        return super.dispatchKeyEvent(event);
    }

    /**
     * Called when a key was pressed down and not handled by any of the views
     * inside of the activity
     * @param keyCode
     *            integer for the corresponding key
     * @param event
     *            KeyEvent occured
     * @return boolean true if key is handled
     */
    @Override
    public boolean onKeyDown(final int keyCode, final KeyEvent event) {

        Log.d(TAG, "onKeyDown() KeyCode : " + keyCode);
        Log.d(TAG, "onKeyDown() KeyCode : " + event);

        if (event.getScanCode() == EXIT_KEY) {
            WidgetManager.exitFromApp(mContext);
        }

        if (Wrapper.getWrapperInstance().isTunerInput()) {
            /*
             * If EAS event has not occurred, flag is set to true and Key
             * handling is normal.If EAS event has occurred, flag is set to
             * false and none of the keys are handled.
             */
            if (!Wrapper.getWrapperInstance().isEASEnabled()) {

                switch (keyCode) {
                    case KeyEvent.KEYCODE_MEDIA_NEXT:
                    case KeyEvent.KEYCODE_CHANNEL_UP:
                       /* if (Wrapper.getWrapperInstance()
                                .allowChannelUpDown(getEnabledChannelList())) {
                            Wrapper.getWrapperInstance().pauseCC();
                            Wrapper.getWrapperInstance().doChannelUp(mContext);
                            return true;
                        }*/
                    case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
                    case KeyEvent.KEYCODE_CHANNEL_DOWN:
                        /*if (Wrapper.getWrapperInstance()
                                .allowChannelUpDown(getEnabledChannelList())) {
                            Wrapper.getWrapperInstance().pauseCC();
                            Wrapper.getWrapperInstance().doChannelDown(mContext);
                            return true;
                        }*/
                }
            }
        }

        return super.onKeyDown(keyCode, event);
    }

   /* private List<ChannelDetails> getEnabledChannelList() {
        if (mChList == null) {
            mChList = TvFramework.getInstance().getLiveTvInstance().getEnabledChannelList();
        }
        return mChList;
    }*/
}
